//
//  ManagerHttpBase.m
//  MIT_itrade
//
//  Created by wanc on 14-4-2.
//  Copyright (c) 2014年 ___ZhengDaXinXi___. All rights reserved.
//

#import "ManagerHttpBase.h"
#import <SystemConfiguration/SystemConfiguration.h>
//Vendor
#import "SaveDataInKeychain.h"
//utils
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "AppDelegate.h"

#define NET_WORK_ALERT 999

@implementation ManagerHttpBase

+ (instancetype)sharedManager {
    static ManagerHttpBase *_sharedManager = nil;
    static dispatch_once_t onceToken;
    
    //获取地址
    NSString *baseUrl = baseServerUrl;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[ManagerHttpBase alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];
        _sharedManager.requestSerializer.timeoutInterval = 10;//设置超时时间
        //_sharedManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    });
    return _sharedManager;
}



//监测网络的可达性
- (void)managerReachability
{
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    
    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager startMonitoring];
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                
                [operationQueue setSuspended:NO];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                [operationQueue setSuspended:NO];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable:
            default:
            {
          
                [operationQueue setSuspended:YES];
            }
                break;
        }
    }];
    
}




//是否被暂停-暂停表示网络不可用
- (BOOL)isNetworkConnect {
    return [ManagerGlobeUntil sharedManager].isNetworkReachability;
}

//是否注册
- (BOOL)isRegister
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey: Phone_Signature];
}


#pragma mark - 基础接口
- (AFHTTPRequestOperation*)customPOST:(NSString *)URLString
                           parameters:(NSMutableDictionary *)parameters
                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
    AFHTTPRequestOperationManager *manager = [ManagerHttpBase sharedManager];
    return [manager POST:URLString parameters:parameters success:success failure:failure];
}

#pragma mark -通用接口

- (AFHTTPRequestOperation*)parameters:(NSMutableDictionary *)parameters
                           customPOST:(NSString*)postAddress
                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success;
{
    
    if ([self isRegister] && [self isNetworkConnect])
    {
        //添加设备识别码
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [parameters setObject:[userDefaults objectForKey: Phone_Signature] forKey:@"SIGNATURE"];
        return [self customPOST:postAddress parameters:parameters
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            NSString *state =[responseObject objectForKey:@"STATE"];
            //单人登陆(状态108)
            if ([state isEqualToString:@"108"]&&![ManagerGlobeUntil sharedManager].singleLogin)
            {
                [ManagerGlobeUntil sharedManager].singleLogin = YES;
                NSString *msg =[responseObject objectForKey:@"MSG"];
                
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg
                                                               delegate:(id<UIAlertViewDelegate>)self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
            }
            else
            {
                if (success) {
                    success(operation,responseObject);
                }
            }
        }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
                {
                    [[ManagerGlobeUntil sharedManager] hideHUD];
                }];
    } else {
        
        [[ManagerGlobeUntil sharedManager] hideHUD];
        return nil;
    }
}
//将错误块开放的基础请求接口
- (AFHTTPRequestOperation*)parameters:(NSMutableDictionary *)parameters
                           customPOST:(NSString*)postAddress
                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                              failure:(void (^)(bool isFailure))failure;

{
    if ([self isRegister]&& [self isNetworkConnect])
    {
        //添加设备识别码
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [parameters setObject:[userDefaults objectForKey: Phone_Signature] forKey:@"SIGNATURE"];
        return [self customPOST:postAddress parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
                {
                    NSString *state =[responseObject objectForKey:@"STATE"];
                    //单人登陆
                    if ([state isEqualToString:@"108"]&&![ManagerGlobeUntil sharedManager].singleLogin)
                    {
                        [ManagerGlobeUntil sharedManager].singleLogin = YES;
                        NSString *msg =[responseObject objectForKey:@"MSG"];
                        
                        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg
                                                                       delegate:(id<UIAlertViewDelegate>)self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }
                    else
                    {
                        if (success) {
                            success(operation,responseObject);
                        }
                    }
                }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
                {
                    [[ManagerGlobeUntil sharedManager] hideHUD];
                    if (failure) {
                        failure(YES);
                    }
                }];
    } else {
        [[ManagerGlobeUntil sharedManager] hideHUD];
        return nil;
    }
}
#pragma mark - rigister-注册
//注册单独请求接口
- (AFHTTPRequestOperation*)rigisterAppSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    /*
     ADAPTER    业务适配器
     BRAND      品牌
     Model      型号
     OS         操作系统
     OSVERSION  系统版本
     SCREEN     屏幕尺寸
     RESOLUTION 分辨率
     MIDU       屏幕密度
     UQID       设备识别号
     OSID       系统ID号:Android专用
     TVERSION   终端版本号:客户端当前使用的版本号
     TYPE       终端类型 A.Android B.iPhone C.iPad
     */
    
    //保持uuid的唯一性-一台手机只保存一份uuid
    NSString *uuid = [[SaveDataInKeychain show:KEYCHAIN_UUID_KEY] objectForKey:KEYCHAIN_UUID_KEY];
    if (!uuid)
    {
        uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [SaveDataInKeychain save:KEYCHAIN_UUID_KEY data:@{KEYCHAIN_UUID_KEY:uuid}];
    }
    
    NSString *SCREEN = [NSString stringWithFormat:@"%.f,%.f",[[UIScreen mainScreen]bounds].size.width,[[UIScreen mainScreen]bounds].size.height];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:@"iPhone" forKey:@"BRAND"];
    [parameter setObject:[[UIDevice currentDevice] model] forKey:@"MODEL"];
    [parameter setObject:[[UIDevice currentDevice] systemName] forKey:@"OS"];
    [parameter setObject:[[UIDevice currentDevice] systemVersion] forKey:@"OSVERSION"];
    [parameter setObject:SCREEN forKey:@"SCREEN"];
    [parameter setObject:SCREEN forKey:@"RESOLUTION"];
    [parameter setObject:@"" forKey:@"MIDU"];
    [parameter setObject:uuid forKey:@"UQID"];
    [parameter setObject:@"" forKey:@"OSID"];
    [parameter setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"TVERSION"];
    [parameter setObject:@"B" forKey:@"TYPE"];
    
    return [self customPOST:@"common/regist?" parameters:parameter success:success failure:failure];
}

//检测更新接口
- (AFHTTPRequestOperation*)rigisterTestingUpdate:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    /*
     ADAPTER	业务适配器	区分大小写
     TYPE	类别	A.Android B.iPhone C.iPad
     VERSION	版本号	客户端版本号
     SIGNATURE
     */
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setObject:@"B" forKey:@"TYPE"];
    [parameters setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"VERSION"];
    [parameters setObject:[userDefaults objectForKey: Phone_Signature] forKey:@"SIGNATURE"];
    
    return [self POST:@"common/checkVersion" parameters:parameters success:success failure:failure];
}


#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger tag = alertView.tag;
    if (tag == NET_WORK_ALERT)
    {
        switch (buttonIndex) {
            case 0:
                [ManagerGlobeUntil sharedManager].alertIsShow = NO;
                break;
                
            default:
                break;
        }
    } else {
        switch (buttonIndex) {
            case 0:
                [ManagerGlobeUntil sharedManager].singleLogin = NO;
                [[ManagerGlobeUntil sharedManager] clearUserInfoData];
                //发送退出通知
               
                break;
            default:
                break;
        }
    }
}

@end
